package com.kingmed.kmss.common.convert;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingmed.kmss.common.exception.ConvertorException;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

public interface Convertor {
    default <T> T convertTo(Class<T> destin) {
        Object instance;
        try {
            instance = destin.newInstance();
        } catch (IllegalAccessException | InstantiationException var4) {
            throw new ConvertorException(var4.getCause(), new Object[0]);
        }

        BeanUtils.copyProperties(this, instance, destin);
        return (T) instance;
    }

    static <S, T> List<T> convertList(final List<S> listSource, Function<S, T> f) {
        if (listSource != null && listSource.size() != 0) {
            List<T> listBack = new ArrayList(listSource.size());
            Iterator var3 = listSource.iterator();

            while(var3.hasNext()) {
                S object = (S) var3.next();
                T instance = f.apply(object);
                listBack.add(instance);
            }

            return listBack;
        } else {
            return Collections.emptyList();
        }
    }

    static <S extends Convertor, T> List<T> convertList(final List<S> listSource, final Class<T> destin) {
        return convertList(listSource, (s) -> {
            return s.convertTo(destin);
        });
    }

    static <S, T> Page<T> convertPage(final Page<S> pageSource, Function<S, T> f) {
        Page<T> pageBack = new Page();
        pageBack.setCurrent(pageSource.getCurrent());
        pageBack.setTotal(pageSource.getTotal());
        pageBack.setSize(pageSource.getSize());
        pageBack.setOrders(pageSource.getOrders());
        pageBack.setPages(pageSource.getPages());
        if (pageSource.getRecords().isEmpty()) {
            return pageBack;
        } else {
            List<T> list = new ArrayList(pageSource.getRecords().size());
            Iterator var4 = pageSource.getRecords().iterator();

            while(var4.hasNext()) {
                S object = (S) var4.next();
                T instance = f.apply(object);
                list.add(instance);
            }

            pageBack.setRecords(list);
            return pageBack;
        }
    }

    static <S extends Convertor, T> Page<T> convertPage(final Page<S> pageSource, final Class<T> destin) {
        return convertPage(pageSource, (s) -> {
            return s.convertTo(destin);
        });
    }
}
